﻿/* 调用API函数实现INI配置文件的读写操作
 */

namespace LSLib.IO
{
    using System;
    using System.IO;
    using System.Text;

    public static class IniConfig
    {
        /// <summary> Write ini file
        /// </summary> 
        /// <param name="file">INI配置文件</param>
        /// <param name="section">项目名称(如 [TypeName] )</param> 
        /// <param name="key">键</param> 
        /// <param name="value">值</param> 
        public static void WriteValue(string file, string section, string key, string value)
        {
            string dir = Path.GetDirectoryName(file);
            if (Directory.Exists(dir) == false) throw new DirectoryNotFoundException(string.Format("找不到配置文件的目录！\r\n{0}", dir));

            API.IO.WritePrivateProfileString(section, key, value, file);
        }

        /// <summary> Read ini file
        /// </summary> 
        /// <param name="file">INI配置文件</param>
        /// <param name="section">项目名称(如 [TypeName] )</param> 
        /// <param name="key">键</param> 
        /// <param name="bufSize">缓存区大小</param>
        public static string ReadValue(string file, string section, string key, int bufSize)
        {
            if (File.Exists(file) == false) throw new FileNotFoundException("配置文件不存在！", file);
            if (bufSize < 0) throw new ArgumentOutOfRangeException("bufSize", bufSize, "bufSize 不能为负数！");

            StringBuilder strVal = new StringBuilder(bufSize);
            string defValue = Guid.NewGuid().ToString();
            API.IO.GetPrivateProfileString(section, key, defValue, strVal, (uint)bufSize, file);
            string result = strVal.ToString();
            return (defValue == result) ? null : result;
        }
    }
}
